import requests
import os
import argparse
from PIL import Image
import matplotlib.pyplot as plt

def detect_face(image_path, api_url="http://localhost:5000/detect"):
    """
    调用API检测人脸
    
    Args:
        image_path: 图像文件路径
        api_url: API端点URL
        
    Returns:
        API返回的结果
    """
    # 检查文件是否存在
    if not os.path.exists(image_path):
        print(f"错误: 图像文件不存在: {image_path}")
        return None
    
    # 打开并显示图像
    try:
        image = Image.open(image_path)
        plt.figure(figsize=(8, 8))
        plt.imshow(image)
        plt.axis('off')
        plt.title("测试图像")
        plt.show()
    except Exception as e:
        print(f"图像打开失败: {str(e)}")
    
    # 准备文件上传
    files = {'file': (os.path.basename(image_path), open(image_path, 'rb'), 'image/jpeg')}
    
    # 发送请求
    try:
        response = requests.post(api_url, files=files)
        
        # 检查响应
        if response.status_code == 200:
            result = response.json()
            print("\n检测结果:")
            print(f"结论: {result['label']}")
            print(f"置信度: {result['confidence']*100:.2f}%")
            print(f"原始概率值: {result['probability']:.4f}")
            return result
        else:
            print(f"API请求失败: {response.status_code} - {response.text}")
            return None
    except Exception as e:
        print(f"请求异常: {str(e)}")
        return None
    finally:
        # 关闭文件
        files['file'][1].close()

if __name__ == "__main__":
    # 设置命令行参数
    parser = argparse.ArgumentParser(description="人脸真伪检测客户端示例")
    parser.add_argument("--image", type=str, required=True, help="要检测的图像文件路径")
    parser.add_argument("--url", type=str, default="http://localhost:5000/detect", help="API端点URL")
    
    args = parser.parse_args()
    
    # 调用API
    detect_face(args.image, args.url) 